import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DeleteOutlined, ExportOutlined } from '@ant-design/icons';
import { Button, Card, Modal, message, Popconfirm } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import DealModal from './dealModal'
import HistoryModal from './historyModal'
import WarningDetail from '../warningDetail';

const mapStateToProps = (state: any) => ({
  batteryMonitorWarningVehicle: state.batteryMonitorWarningVehicle,
  loading: state.loading.effects['batteryMonitorWarningVehicle/getFetchPage'],
});
class HighRiskTab extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    //  level: 0:低; 1:中; 2:高
    this.state = {
      formValues: {
        level: 2
      },
      brandList: [], // 品牌
      seriesList: [], //  车系
      vehicleTypeList: [],  //  车型
      dealModalVisible: false, //  预警处理弹框
      currentDealVin: '',
      historyModalVisible: false, //  历史弹框
      currentHistoryVin: '',
      detailFlag: 'vehicle',
      currentDetailVin: '',
      detailModalVisible: '',  //  详情弹框
      // upModalVisible: false,  //  升级弹框
      currentVehicleVin: '',
      downModalVisible: false,  //  降级弹框
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      page: 1,
      size: 10,
    };
    dispatch({
      type: 'batteryMonitorWarningVehicle/getFetchPage',
      payload: { 
        url: '/battery/monitor/vehicle/page',
        ...formValues,
        ...params
      },
    });

    this.getBrandData()
  }

  //  获取品牌数据列表
  getBrandData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batteryMonitorWarningVehicle/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            brandList: res.data.map((item: any) => ({
              label: item.brandName,
              value: item.brandCode
            })),
            seriesList: [],
            vehicleTypeList: [],
          })
        }
      }
    })
  }

  //  获取车系数据列表
  getSeriesData = (t: any) => {
    const { dispatch } = this.props;
    const brandId = this.searchForm.current.getFieldValue('brandCode')
    //  重置车系、车型
    this.searchForm.current.resetFields(['seriesCode', 'typeCode']);
    this.setState({
      seriesList: [],
      vehicleTypeList: [],
    })
    brandId && dispatch({
      type: 'batteryMonitorWarningVehicle/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        this.setState({
          seriesList: res.data.map((item: any) => ({
            label: item.name,
            value: item.code,
          })),
        });
      },
    })
  }

  //  获取车型数据列表
  getVehicleTypeData = (t: any) => {
    const { dispatch } = this.props;
    this.setState({ vehicleTypeList: [] });
    this.searchForm.current.resetFields(['typeCode']);
    const brandId = this.searchForm.current.getFieldValue('brandCode');
    const seriesId = this.searchForm.current.getFieldValue('seriesCode');
    //  重置车型
    brandId && seriesId && 
      dispatch({
        type: 'batteryMonitorWarningVehicle/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: (res: any) => {
          this.setState({
            vehicleTypeList: res.data.map((item: any) => ({
              label: item.name,
              value: item.code,
            })),
          });
        }
      })
  }

  //  更新列表
  handleRefreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'batteryMonitorWarningVehicle/getFetchPage',
      payload: { url: '/battery/monitor/vehicle/page', ...formValues },
    });
  }

  handleFormReset = () => {
    this.setState({
      formValues: {
        level: 2
      },
      seriesList: [],
      vehicleTypeList: [],
    })
  }

  //  预警处理弹框（打开）
  openDealModal = (record: any) => {
    this.setState({
      dealModalVisible: true,
      currentDealVin: record.vin,
    })
  }

  //  预警处理弹框（关闭）
  closeDealModal = () => {
    this.setState({
      dealModalVisible: false,
      currentDealVin: '',
    });
  }

  //  处理历史弹框（打开）
  openHistoryModal = (record: any) => {
    this.setState({
      historyModalVisible: true,
      currentHistoryVin: record.vin,
    })
  }

  //  处理历史弹框（关闭）
  closeHistoryModal = () => {
    this.setState({
      historyModalVisible: false,
      currentHistoryVin: '',
    });
  }

  //  预警详情弹框（打开）
  openDetailModal = (record: any) => {
    this.setState({
      currentDetailVin: record.vin,
      detailModalVisible: true,
    })
  }

  //  预警详情弹框（关闭）
  closeDetailModal = () => {
    this.setState({
      currentDetailVin: '',
      detailModalVisible: false,
    });
  }

  //  升级弹框（打开）
  /* openUpModal = () => {
    this.setState({
      upModalVisible: true
    })
  } */

  //  升级弹框（关闭）
  /* closeUpModal = () => {
    this.setState({
      upModalVisible: false
    })
  } */

  //  降级弹框（打开）
  openDownModal = (record: any) => {
    this.setState({
      currentVehicleVin: record.vin,
      downModalVisible: true
    })
  }

  //  降级弹框（关闭）
  closeDownModal = () => {
    this.setState({
      currentVehicleVin: '',
      downModalVisible: false
    })
  }

  // 降级 0
  handleDegrade = (flag: any) => {
    const { dispatch } = this.props;
    const { currentVehicleVin } = this.state
    const params = {
      vin: currentVehicleVin,
      flag,
    }
    dispatch({
      type: 'batteryMonitorWarningVehicle/putObjWithRes',
      payload: {
        url: '/battery/monitor/vehicle/warning/upOrDown',
        ...params,
      },
      callback: (response: any) => {
        this.closeDownModal()
        this.handleRefreshPage()
      }
    })
  }

  render() {
    const { batteryMonitorWarningVehicle: {
      pageData: { list, pagination },
    }, loading, pathname, permissions } = this.props
    const { formValues, brandList, seriesList, vehicleTypeList, dealModalVisible, currentDealVin, historyModalVisible, currentHistoryVin, detailModalVisible, upModalVisible, downModalVisible, currentDetailVin, detailFlag } = this.state;
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    }

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page?.total}&nbsp;条</span>
      ),
    }

    const columns = [
      {
        title: 'VIN码',
        dataIndex: 'vin',
      },
      {
        title: '总预警次数',
        dataIndex: 'warningCount',
      },
      {
        title: '已处理预警数',
        dataIndex: 'handledWarning',
        render: (text: any, record: any) => {
          return record?.warningCount - record?.unhandledWarningCount
        }
      },
      {
        title: '工单数',
        dataIndex: 'orderCount',
      },
      {
        title: '未处理预警数',
        dataIndex: 'unhandledWarningCount',
      },
      {
        title: '未结束工单数',
        dataIndex: 'unhandledOrderCount',
      },
      {
        title: '是否自燃',
        dataIndex: 'selfIgnitionStatus',
        render: (text: any) => {
          return text == 1 ? '是' : text == '0' ? '否' : '';
        }
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 240,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '预警详情',
              key: 'detail',
              auth: 'warningVehicle_doDetail',
              onConfirm: () => {
                this.openDetailModal(record)
              },
            },
            {
              title: '预警处理',
              key: 'deal',
              auth: 'warningVehicle_doDeal',
              hide: !(record.unhandledWarningCount > 0),
              onConfirm: () => {
                this.openDealModal(record)
              },
            },
            {
              title: '风险降级',
              key: 'down',
              auth: 'warningVehicle_doDown',
              onConfirm: () => {
                this.openDownModal(record)
              },
            },
            {
              title: '处理历史',
              key: 'history',
              auth: 'warningVehicle_doHistory',
              onConfirm: () => {
                this.openHistoryModal(record)
              },
            }
          ]
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        }
      }
    ];
    
    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        onChange: (e: any) => {
          this.getSeriesData(e)
        },
        keyValue: ['value', 'label'],
        key: 'brandCode'
      },
      {
        title: '车系',
        type: 'select',
        selectOptions: seriesList,
        onChange: (e: any) => {
          this.getVehicleTypeData(e)
        },
        keyValue: ['value', 'label'],
        key: 'seriesCode'
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: vehicleTypeList,
        key: 'typeCode'
      },
      {
        title: 'VIN',
        type: 'input',
        key: 'vin',
        maxLength: 18,
      },
      {
        title: '是否有未处理预警',
        type: 'select',
        selectOptions: [
          {
            value: 0, label: '无未处理预警',
          },
          {
            value: 1, label: '有未处理预警',
          }
        ],
        key: 'warningStatus',
      },
      {
        title: '是否有未结束工单',
        type: 'select',
        selectOptions: [
          {
            value: 0, label: '无未结束工单',
          },
          {
            value: 1, label: '有未结束工单',
          }
        ],
        key: 'orderStatus',
      },
    ]

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      // rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    };

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'batteryMonitorWarningVehicle/getFetchPage',
              url: '/battery/monitor/vehicle/page',
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            extraArgs={{level: 2}}
            handleFormReset={() =>
              this.setState({
                formValues: {
                  level: 2
                },
              })
            }
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            currentName={"page"}
            pageSizeName={"size"}
            tableProps={tableProps}
            fetchParams={{ type: 'batteryMonitorWarningVehicle/getFetchPage', url: '/battery/monitor/vehicle/page', extraArgs: {level: 2} }}
            formValues={formValues}
          />
        </Card>
        <DealModal
          onRef={(val: any) => (this.dealModal = val)}
          vin={currentDealVin}
          modalVisible={dealModalVisible}
          closeModal={this.closeDealModal}
          refreshPage={this.handleRefreshPage}
        />
        <HistoryModal 
          onRef={(val: any) => (this.historyModal = val)}
          vin={currentHistoryVin}
          modalVisible={historyModalVisible}
          closeModal={this.closeHistoryModal}
        />
        <WarningDetail
          flag={detailFlag}
          param={currentDetailVin}
          modalVisible={detailModalVisible}
          closeModal={this.closeDetailModal}
        />
        <Modal
          title="风险降级"
          centered
          visible={downModalVisible}
          onOk={() => {
            this.handleDegrade(0)
          }}
          onCancel={() => {
            this.closeDownModal()
          }}
          width={700}
        >
          <p>确定要降低该车辆风险等级为中级吗？</p>
        </Modal>
      </div>
    )
  }
}
export default connect(mapStateToProps)(HighRiskTab);
